package com.memeuxe.awtrix.util;

import com.memeuxe.awtrix.entity.Command;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.time.Duration;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.temporal.TemporalUnit;
import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@Slf4j
public class CommandSendThread extends Thread {
    private CommandHttpSend commandHttpSend;

    public CommandSendThread(CommandHttpSend commandHttpSend) {
        this.commandHttpSend = commandHttpSend;
    }

    @Override
    public void run() {
        Command command = null;
        boolean success = false;
        Instant now = Instant.now();
        Duration duration;
        long betweenTime;
        while (true){
            log.info("while run");
            now = Instant.now();
            //上次结束的时间是当前时间之后
            if(CommandCache.lastRunEndTime.isAfter(now)){
                duration = Duration.between(CommandCache.lastRunEndTime, now);
                betweenTime = duration.getSeconds();
                try {
                    if(betweenTime<0){
                        betweenTime *= -1;
                    }
                    log.info("等待{}", betweenTime);
                    sleep(betweenTime * 1000);
                    continue;
                } catch (InterruptedException e) {
                    log.error("sleep error", e);
                }
            }
            try {
                command = CommandCache.commandQueue.poll(1, TimeUnit.MINUTES);
                if(command == null){
                    continue;
                }
            } catch (InterruptedException e) {
                log.error("commandQueue.poll error", e);
            }
            try {
                success = commandHttpSend.send2Awtrix(command);
            } catch (Exception e) {
                log.error("send2Awtrix error", e);
            }
            if(success){
                CommandCache.lastRunEndTime = now.plusSeconds(command.getExpend() * 60);
            }
        }
    }
}
